package club.pinea.handler.login;

import club.pinea.annotations.Head;
import club.pinea.constants.RedisPrefix;
import club.pinea.interfaces.TCPMessage;
import club.pinea.model.User;
import club.pinea.proto.BasicProto;
import club.pinea.proto.CommandProto;
import club.pinea.proto.UserProto;
import club.pinea.send.MessageSend;
import club.pinea.service.UserService;
import club.pinea.session.IOSession;
import club.pinea.utils.RedisCache;
import club.pinea.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 登录处理
 */
@Head(CommandProto.Command.C_S_LOGIN_VALUE)
@Component
public class LoginHandler implements TCPMessage<BasicProto.BaseMessage> {
    // 用户接口
    @Autowired
    private UserService loginUserService;

    // Redis操作接口
    @Autowired
    private RedisCache redisCache;

    @Value("${server.lobby.host}")
    public String lobbyHost;

    @Value("${server.lobby.port}")
    public Integer lobbyPort;

    @Override
    public void doMessage(BasicProto.BaseMessage msg, IOSession session) throws Exception {
        UserProto.LoginRequest loginRequest = UserProto.LoginRequest.parseFrom(msg.getBody());
        String name = loginRequest.getName();
        String pass = loginRequest.getPass();
        //调用service中的方法验证用户信息，并返回完整的用户信息
        User u = null;
        try{
            u = loginUserService.userLogin(name, pass);
        }catch (IllegalStateException e){
            e.printStackTrace();
            BasicProto.Res res = BasicProto.Res.newBuilder()
                    .setStatus(0)
                    .setDesc(e.getMessage())
                    .build();

            UserProto.LoginResponse loginResponse = UserProto.LoginResponse.newBuilder()
                    .setLobbyPort(lobbyPort)
                    .setLobbyHost(lobbyHost)
                    .setRes(res)
                    .build();
            MessageSend.sendToUser(loginResponse, session);
            return;

        }

        //判断是否是正确的User对象，如果为空则返回失败信息，否则返回正确信息以及端口号和用户对象
        if (u == null) {
            BasicProto.Res res = BasicProto.Res.newBuilder()
                    .setStatus(0)
                    .setDesc("登录失败，用户名或密码错误")
                    .build();

            UserProto.LoginResponse loginResponse = UserProto.LoginResponse.newBuilder()
                    .setLobbyPort(lobbyPort)
                    .setLobbyHost(lobbyHost)
                    .setRes(res)
                    .build();
            MessageSend.sendToUser(loginResponse, session);
            return;
        }
        String token = StringUtils.getToken4User();
        redisCache.setCacheObject(RedisPrefix.TOKEN_PREFIX + u.getId(), token);
        redisCache.setCacheObject(RedisPrefix.USER_INFO_PREFIX + u.getId(), u);
        Date d = new Date();
        //判断年份月份和天数是否都一致
        if (!(u.getLastPlayTime().getDate() == d.getDate() && u.getLastPlayTime().getMonth() == d.getMonth() && u.getLastPlayTime().getYear() == d.getYear())) {//判断上一次游戏时间是否是上一天，如果超过一天则重置留机次数
            u.setStaySeatTime(3);
        }
        BasicProto.Res res = BasicProto.Res.newBuilder()
                .setStatus(1)
                .setDesc("success")
                .build();
        UserProto.User user = UserProto.User.newBuilder()
                .setId(u.getId())
                .setMoney(u.getMoney())
                .setStatus(u.getStatus())
                .setStaySeatTime(u.getStaySeatTime())
                .setToken(token)
                .setUsername(u.getUsername())
                .build();
        UserProto.LoginResponse loginResponse = UserProto.LoginResponse.newBuilder()
                .setLobbyPort(lobbyPort)
                .setLobbyHost(lobbyHost)
                .setRes(res)
                .setUser(user)
                .build();

        loginUserService.updateUserIp(u, session.getIp());
        MessageSend.sendToUser(loginResponse, session);
    }
}
